package com.united.ucts.modules.auth.controller;

import com.nimbusds.jose.jwk.JWKSet;
import com.nimbusds.jose.jwk.RSAKey;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.security.KeyPair;
import java.security.interfaces.RSAPublicKey;
import java.util.Map;

/**
 * 获取RSA公钥接口
 * 需要注意的是,增加此接口后,需要配置Spring Security,允许获取公钥接口的访问
 * 具体的配置在 WebSecurityConfig 类中,需要在该类的configure方法中
 *
 * @author hudan
 * @version 1.0
 * @filename KeyPairController.java
 * @copyright <a href="www.united.cn">www.united.cn</a>
 * @date 2019-10-10
 */
@Slf4j
@RequiredArgsConstructor
@Api(value = "KeyPairController", tags = "获取RSA公钥接口")
@RestController
@RequestMapping("/rsa")
public class KeyPairController {

    private final KeyPair keyPair;

    /**
     * 获取非对称加密（RSA）算法公钥
     *
     * @return 非对称加密公钥对象信息
     */
    @ApiOperation("获取RSA公钥")
    @GetMapping("/publicKey")
    public Map<String, Object> getKey() {
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        RSAKey key = new RSAKey.Builder(publicKey).build();
        return new JWKSet(key).toJSONObject();
    }
}